﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using Dapper.Contrib.Extensions;
using pinduoduo.Model;
using pinduoduo.Service;
using pinduoduo.Util;
using Sunny.UI;
using Tk.Soc.Share.Common.Helpers;
using Utils;

namespace pinduoduo.Page
{
    public partial class MainAccountPage : UIPage
    {

        private ChromiumWebBrowser AccountChromeBrowser;
        private RequestContext AccountContext;
        private PddTokenService pddTokenService;
        private Main mainForm;
        public MainAccountPage(Main mainForm)
        {
            this.mainForm = mainForm;
            InitializeComponent();
            pddTokenService = new PddTokenService();
            InitializeAccountChromium();
            InitUserDataGridView();
        }

        /// <summary>
        /// 初始化UserDataGridView
        /// </summary>
        private void InitUserDataGridView()
        {
            UserDataGridView.AddCheckBoxColumn("选择", "IsCheck").SetFixedMode(50);
            UserDataGridView.AddColumn("序号", "num").SetFixedMode(50);
            UserDataGridView.AddColumn("用户ID", "pdd_user_id").SetFixedMode(130);
            UserDataGridView.AddColumn("最近订单", "last_order_sn");
            UserDataGridView.AddColumn("状态", "status").SetFixedMode(50);
            UserDataGridView.AutoGenerateColumns = false;
            UserDataGridView.ReadOnly = true;
            var tokens = pddTokenService.GetShuaDanToken();
            UserDataGridViewPagination.DataSource = tokens;
            UserDataGridViewPagination.ActivePage = 1;
        }

        public void UpdateData()
        {
            var tokens = pddTokenService.GetShuaDanToken();
            UserDataGridViewPagination.DataSource = tokens;
            UserDataGridViewPagination.ActivePage = 1;
        }


        //初始化浏览器并启动
        public void InitializeAccountChromium()
        {

            AccountContext = CefUtils.GetAccountContext();

            AccountChromeBrowser = new ChromiumWebBrowser("http://yangkeduo.com/", AccountContext);
#if DEBUG
            AccountChromeBrowser.KeyboardHandler = new CEFKeyBoardHander();
#endif
            this.uiPanel1.Controls.Add(AccountChromeBrowser);

            AccountChromeBrowser.Dock = DockStyle.Fill;
        }

        private async void uiButton1_Click(object sender, EventArgs e)
        {
            await AccountContext.GetCookieManager(null).FlushStoreAsync();

            List<CefSharp.Cookie> cookies2 = await AccountContext.GetCookieManager(null).VisitUrlCookiesAsync("http://mobile.yangkeduo.com", true);
            List<CefSharp.Cookie> cookies = await AccountContext.GetCookieManager(null).VisitAllCookiesAsync();
            if (cookies == null || cookies.Count == 0)
            {
                ShowErrorDialog("请先登录账号");
                return;
            }

            CefSharp.Cookie PDDAccessTokenCookie = cookies.Where(x => { return x.Name == "PDDAccessToken"; }).FirstOrDefault();
            CefSharp.Cookie pdd_user_id_cookie = cookies.Where(x => { return x.Name == "pdd_user_id"; }).FirstOrDefault();
            if (PDDAccessTokenCookie == null || pdd_user_id_cookie == null)
            {
                ShowErrorDialog("请先登录账号");
                return;
            }
            PddToken pddToken = pddTokenService.GetAllToken().Where(x => x.account_type == 1).FirstOrDefault();
            if (pddToken == null)
            {
                pddToken = new PddToken();
                pddToken.PDDAccessToken = PDDAccessTokenCookie.Value;
                pddToken.pdd_user_id = pdd_user_id_cookie.Value;
                pddToken.account_type = 1;
                long id = pddTokenService.InsertToken(pddToken, true);
                if (id > 0) { ShowSuccessDialog("设置成功"); }
            }
            else
            {
                pddToken.PDDAccessToken = PDDAccessTokenCookie.Value;
                pddToken.pdd_user_id = pdd_user_id_cookie.Value;
                pddToken.account_type = 1;
                bool reslut = pddTokenService.UpdateToken(pddToken, true);
                if (reslut) { ShowSuccessDialog("设置成功"); }

            }
            mainForm.mainPage.AccountPddToken = pddToken;
        }
 
        private  async void uiButton2_Click(object sender, EventArgs e)
        {
            if (ShowAskDialog("您确定退出登录吗", "提示框"))
            {
                await AccountContext.GetCookieManager(null).DeleteCookiesAsync();
            }
        }

        private async void uiButton3_Click(object sender, EventArgs e)
        {
            string pddurl = "http://yangkeduo.com/";
            await AccountContext.GetCookieManager(null).DeleteCookiesAsync(pddurl, "PDDAccessToken");
            await AccountContext.GetCookieManager(null).DeleteCookiesAsync(pddurl, "pdd_user_id");

            AccountChromeBrowser.Load("http://yangkeduo.com/login.html");
        }

        private void uiButton6_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.txt)|*.txt";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                string text = File.ReadAllText(file);
                if (string.IsNullOrWhiteSpace(text))
                {
                    MessageBox.Show("数据为空");
                    return;
                }
                string[] striparr = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                var PddTokenList = pddTokenService.GetAllToken();
                foreach (var item in striparr)
                {
                    try
                    {
                        string[] sArray1 = item.Split(new char[4] { '-', '-', '-', '-' }, StringSplitOptions.RemoveEmptyEntries);
                        if (sArray1.Length != 3)
                        {
                            continue;
                        }
                        string qqOrPhone = sArray1[0];
                        string uid = sArray1[1];
                        string token = sArray1[2];
                        PddToken pddToken = new PddToken();
                        pddToken.pdd_user_id = uid;
                        pddToken.PDDAccessToken = token;
                        var pddT = PddTokenList.Where(x =>
                        {
                            return x.pdd_user_id == uid;
                        }).FirstOrDefault();
                        if (pddT != null)
                        {
                            pddToken.id = pddT.id;
                            pddTokenService.UpdateToken(pddToken);
                            //DataBaseHelper.SqLiteDBCon.Update<PddToken>(pddToken);
                        }
                        else
                        {
                            pddTokenService.InsertToken(pddToken);
                            //var reslut = DataBaseHelper.SqLiteDBCon.Insert<PddToken>(pddToken);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Logger.Error("导入小号失败", ex);
                    }

                }

                var tokens = pddTokenService.GetShuaDanToken();
                UserDataGridViewPagination.DataSource = tokens;
                UserDataGridViewPagination.ActivePage = 1;
            }
        }

        private void uiButton5_Click(object sender, EventArgs e)
        {
            var pddTokenList = GetSelectRows();
            if (pddTokenList.Count() < 1)
            {
                ShowWarningDialog("请先勾选要删除的数据");
                return;
            }

            if (ShowAskDialog("您确定删除这" + pddTokenList.Count() + "个小号吗?"))
            {
                foreach (var pddToken in pddTokenList)
                {
                    bool reslut = DataBaseHelper.SqLiteDBCon.Delete(pddToken);
                }
                var tokens = pddTokenService.GetShuaDanToken();
                UserDataGridViewPagination.DataSource = tokens;
            }
        }

        public IEnumerable<PddToken> GetSelectRows()
        {
            var pddTokens = new List<PddToken>();
            foreach (DataGridViewRow dataGridViewRow in this.UserDataGridView.Rows)
            {
                var pddToken = dataGridViewRow.DataBoundItem as PddToken;
                if (pddToken.IsCheck)
                {
                    pddTokens.Add(pddToken);
                }
            }
            return pddTokens;
        }


        private void UserDataGridView_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.Cells[1].Value = string.Format("{0}", (e.Row.Index + 1) + (this.UserDataGridViewPagination.ActivePage - 1) * UserDataGridViewPagination.PageSize);
        }

        private async void UserDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            PddToken pddToken = this.UserDataGridView.Rows[e.RowIndex].DataBoundItem as PddToken;

            if (pddToken == null)
            {
                return;
            }

            DataGridViewCheckBoxCell dataGridViewCheckBoxCell = (DataGridViewCheckBoxCell)(this.UserDataGridView.Rows[this.UserDataGridView.CurrentCell.RowIndex].Cells[0]);
            if (Convert.ToBoolean(dataGridViewCheckBoxCell.EditedFormattedValue) == false)
            {
                dataGridViewCheckBoxCell.Value = true;
            }
            else
            {
                dataGridViewCheckBoxCell.Value = false;
            }


            if (!string.IsNullOrWhiteSpace(pddToken.PDDAccessToken))
            {
                pddToken = await pddTokenService.CheckePddTokenStatus(pddToken);
                //var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken);

                //if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.OK)
                //{
                //    pddToken.status = "正常";
                //}
                //else if (pddUserInfo.Content.Contains("error_code"))
                //{
                //    pddToken.status = "过期";
                //}
                //else if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.NotFound)
                //{
                //    pddToken.status = "未知";
                //}
                //pddTokenService.UpdateToken(pddToken, true);

            }
            else
            {
                pddToken.status = "未知";
            }
            this.UserDataGridView.Refresh();

            string isBrowseToken = IniHelper.GetPrivateProfileString("STARTUP", "isBrowseToken", IniHelper.IniPathFile, 500);
       
#if DEBUG
            SetToken(pddToken);
            string url = "http://yangkeduo.com/";
            AccountChromeBrowser.Load(url);
#else
     if (isBrowseToken == "true")
            {
                SetToken(pddToken);
                string url = "http://yangkeduo.com/";
                AccountChromeBrowser.Load(url);
    }
#endif


        }

        private void uiCheckBox1_ValueChanged(object sender, bool value)
        {
            foreach (DataGridViewRow dataGridViewRow in this.UserDataGridView.Rows)
            {
                var pddToken = dataGridViewRow.DataBoundItem as PddToken;
                pddToken.IsCheck = uiCheckBox1.Checked;
            }
            this.UserDataGridView.Refresh();
        }

        private void UserDataGridViewPagination_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            UserDataGridView.DataSource = pagingSource;
        }

        private async void uiButton4_Click(object sender, EventArgs e)
        {
           var accountContext = new RequestContext(new RequestContextSettings()
            {
                CachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\global1\\",
                PersistSessionCookies = true,
                PersistUserPreferences = true
            });
            await accountContext.GetCookieManager(null).DeleteCookiesAsync();
            await accountContext.GetCookieManager(null).FlushStoreAsync();
             
        }

        private void uiButton7_Click(object sender, EventArgs e)
        {
            PddToken pddToken = pddTokenService.GetAllToken().Where(x => x.account_type == 1).FirstOrDefault();
            if (pddToken == null) 
            {
                ShowWarningDialog("请先登录主账号，再进行浏览，点击旁边的 跳转登录页面");
                return;
            }
            SetToken(pddToken);
        }

        async void SetToken(PddToken pddToken)
        {
            string pddurl = "http://yangkeduo.com/";
            await AccountContext.GetCookieManager(null).DeleteCookiesAsync(pddurl, "PDDAccessToken");
            await AccountContext.GetCookieManager(null).DeleteCookiesAsync(pddurl, "pdd_user_id");

            var PDDAccessToken = new CefSharp.Cookie
            {
                Path = "/",
                Domain = "yangkeduo.com",
                Creation = DateTime.Today,
                Expires = DateTime.Today.AddDays(30),
                Name = "PDDAccessToken",
                Value = pddToken.PDDAccessToken
            };
            var pdd_user_id = new CefSharp.Cookie
            {
                Path = "/",
                Domain = "yangkeduo.com",
                Creation = DateTime.Today,
                Expires = DateTime.Today.AddDays(30),
                Name = "pdd_user_id",
                Value = pddToken.pdd_user_id
            };
            await AccountContext.GetCookieManager(null).SetCookieAsync(pddurl, pdd_user_id);
            await AccountContext.GetCookieManager(null).SetCookieAsync(pddurl, PDDAccessToken);
        }

        private void uiCheckBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private async void uiButton9_Click(object sender, EventArgs e)
        {
            var tokens = pddTokenService.GetShuaDanToken();

            ShowWaitForm();
     
         
            foreach (var pddToken in tokens)
            {
                if (!string.IsNullOrWhiteSpace(pddToken.PDDAccessToken))
                {
                    PddToken  pddTokenNew = await pddTokenService.CheckePddTokenStatus(pddToken);
                    pddToken.status = pddTokenNew.status;
                    //var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken);

                    //if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.OK)
                    //{
                    //    pddToken.status = "正常";
                    //}
                    //else if (pddUserInfo.Content.Contains("error_code"))
                    //{
                    //    pddToken.status = "过期";
                    //}
                    //else if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.NotFound)
                    //{
                    //    pddToken.status = "未知";
                    //}
                }
                else
                {
                    pddToken.status = "未知";
                }
                SetWaitFormDescription(UILocalize.SystemProcessing + " 检查" + pddToken.pdd_user_id);
                pddTokenService.UpdateToken(pddToken, true);
            }

            HideWaitForm();
            UpdateData();
        }

        private void uiButton10_Click(object sender, EventArgs e)
        {
            var tokens = pddTokenService.GetShuaDanToken();
            foreach (var pddToken in tokens)
            {
                if (pddToken.status == "过期")
                {
                    pddTokenService.DelToken(pddToken);
                }
            }
            UpdateData();
        }

        private void uiButton11_Click(object sender, EventArgs e)
        {
            string url = "http://yangkeduo.com/orders.html?type=1&comment_tab=1&combine_orders=1&refer_page_name=personal&refer_page_sn=10001";
            AccountChromeBrowser.Load(url);
        }

        private void uiButton12_Click(object sender, EventArgs e)
        {
            if (ShowAskDialog("是否删除小号最后订单号，注意：不会删除订单")) 
            {
                var tokens = pddTokenService.GetShuaDanToken();
                foreach (var pddToken in tokens)
                {
                    pddToken.last_order_sn = "";
                     
                    pddTokenService.UpdateToken(pddToken, true);
                    
                }
                UpdateData();
            }
        }
    }
}
